import { useParams } from "react-router-dom";
import { useRequest } from "ahooks";
import { getQuestionService } from "../services/question";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { resetComponent } from "../store/componentsReducer";
import { resetPageInfo } from "../store/pageInfoReducer";

function useLoadQuestionData() {
  const dispatch = useDispatch();
  const { id = "" } = useParams();
  const { data, loading, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error();
      return await getQuestionService(id);
    },
    { manual: true }
  );

  useEffect(() => {
    if (!data) return;
    const { title, isPrompt, isPublished, desc, componentList } = data;
    dispatch(
      resetComponent({ componentList, selectedId: "", copiedComponent: null })
    );
    dispatch(resetPageInfo({ title, isPrompt, isPublished, desc }));
  }, [data]);

  useEffect(() => {
    run(id);
  }, [id]);

  return { loading, error };
}
export default useLoadQuestionData;
